package com.chiyoyo.multipay.framework.core.client.impl.alipay.client;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.alipay.api.domain.AlipayTradeCreateModel;
import com.alipay.api.request.AlipayTradeCreateRequest;
import com.alipay.api.response.AlipayTradeCreateResponse;
import com.chiyoyo.multipay.framework.core.client.dto.order.PayOrderRespDTO;
import com.chiyoyo.multipay.framework.core.client.dto.order.PayOrderUnifiedReqDTO;
import com.chiyoyo.multipay.framework.core.client.exception.PayException;
import com.chiyoyo.multipay.framework.core.client.impl.alipay.AbstractAlipayPayClient;
import com.chiyoyo.multipay.framework.core.client.impl.alipay.AlipayPayClientConfig;
import com.chiyoyo.multipay.framework.core.enums.channel.PayChannelEnum;
import com.chiyoyo.multipay.framework.core.enums.order.PayOrderDisplayModeEnum;
import lombok.extern.slf4j.Slf4j;

/**
 * @author chil
 * 支付宝【小程序 支付】的 PayClient 实现类
 * 文档：<a href="https://opendocs.alipay.com/mini/03l5wn?scene=de4d6a1e0c6e423b9eefa7c3a6dcb7a5&amp;pathHash=8bcfc78c">小程序 支付</a>
 */
@Slf4j
public class AlipayLiteClient extends AbstractAlipayPayClient {

    public AlipayLiteClient(AlipayPayClientConfig config) {
        super(PayChannelEnum.ALIPAY_LITE.getCode(), config);
    }

    /**
     * 执行统一下单操作
     *
     * @param reqDTO 统一下单请求DTO
     * @return 支付订单响应DTO
     * @throws Throwable 抛出可能发生的异常
     */
    @Override
    protected PayOrderRespDTO doUnifiedOrder(PayOrderUnifiedReqDTO reqDTO) throws Throwable {
        AlipayTradeCreateModel model = new AlipayTradeCreateModel();
        model.setOutTradeNo(reqDTO.getOutTradeNo());
        model.setTotalAmount(formatAmount(reqDTO.getPrice()));
        model.setSubject(reqDTO.getSubject());
        model.setBuyerId(getBuyerId(reqDTO));
        model.setTimeoutExpress(formatTime(reqDTO.getExpireTime()));

        AlipayTradeCreateRequest request = new AlipayTradeCreateRequest();
        request.setBizModel(model);
        request.setNotifyUrl(reqDTO.getNotifyUrl());

        AlipayTradeCreateResponse response = client.certificateExecute(request);
        if (!response.isSuccess()) {
            return buildClosedPayOrderRespDTO(reqDTO, response);
        }
        return PayOrderRespDTO.waitingOf(PayOrderDisplayModeEnum.APP.getMode(),
                response.getBody(), reqDTO.getOutTradeNo(), response);
    }

    // ========== 各种工具方法 ==========

    static String getBuyerId(PayOrderUnifiedReqDTO reqDTO) {
        String buyerId = MapUtil.getStr(reqDTO.getChannelExtras(), "buyerId");
        if (StrUtil.isEmpty(buyerId)) {
            throw new PayException("支付请求的 buyerId 不能为空！");
        }
        return buyerId;
    }
}
